package lee.vioson.remotedata.repositories

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import lee.vioson.remotedata.ApiServices
import lee.vioson.remotedata.bean.ChapterInfo
import lee.vioson.remotedata.utils.body

/**
 *Author:viosonlee
 *Date:2023/6/16
 *DESCRIPTION:
 */
class BookRepositoryImpl(private val apiServices: ApiServices) :
    BookRepository, BaseRepository() {
    override fun fetchBookDetail(uniqueId: String, bookId: String) = flow {
        val result = handleNotEmptyResponse(
            apiServices.fetchBookDetail(
                mapOf(
                    "uniqueId" to uniqueId,
                    "bookId" to bookId,
                ).body
            )
        )
        emit(result)
    }

    override fun changeCollection(uniqueId: String, addCollection: Boolean, bookId: String) = flow {
        emit(
            handleResponse(
                apiServices.doFavorite(
                    mapOf(
                        "uniqueId" to uniqueId,
                        "bookId" to bookId,
                        "action" to if (addCollection) "add" else "cancel"
                    ).body
                )
            ).success
        )
    }

    override fun doSearch(pageIndex: Int, searchText: String) = flow {
        val result = handleNotEmptyResponse(
            apiServices.doSearch(
                mapOf(
                    "pageIndex" to pageIndex,
                    "pageSize" to pageSize,
                    "searchText" to searchText,
                ).body
            )
        )
        val list = result.list ?: emptyList()
        emit(list)
    }

    override fun markBookView(uniqueId: String, bookId: String) = flow {
        emit(
            handleResponse(
                apiServices.markBookView(
                    mapOf(
                        "uniqueId" to uniqueId,
                        "bookId" to bookId,
                    ).body
                )
            ).success
        )
    }

    override fun chapterDetail(uniqueId: String, chapterId: String): Flow<List<ChapterInfo>> {
        return flow {
            emit(
                handleNotEmptyResponse(
                    apiServices.fetchChapterDetail(
                        mapOf(
                            "uniqueId" to uniqueId,
                            "chapterId" to chapterId,
                        ).body
                    )
                ).list ?: emptyList()
            )
        }
    }
}